package main

import (
	"strconv"
	"strings"

	"gitee.com/haifengat/wxwork-bot/src"
	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/compress"
	"github.com/gofiber/fiber/v2/middleware/logger"
	"github.com/sirupsen/logrus"
)

func main() {
	var app = fiber.New()
	var sent_count = 0

	app.Use(logger.New(logger.Config{
		Format: "[${ip}]:${port} ${status} - ${method} ${path}\n",
	})) // 日志
	app.Use(compress.New()) // 压缩传输

	app.Get("/", func(c *fiber.Ctx) error {
		stat_msg := "wxchat Server is running! \nParsed & forwarded " + strconv.Itoa(sent_count) + " messages to WeChat Work!"
		return c.SendString(stat_msg)
	})

	// msg from apps from develop
	app.Post("/grafana-alert/:key", func(c *fiber.Ctx) error {
		sent_count++
		err := src.SendCard(c)
		if err != nil {
			logrus.Error(err.Error())
		}
		return err
	})

	app.All("/:key/txt", func(c *fiber.Ctx) error {
		sent_count++
		botKey := c.Params("key")
		title := c.Query("title")
		if title == "" {
			title = c.FormValue("title")
		}
		warn := c.Query("warn")
		if warn == "" {
			warn = c.FormValue("warn")
		}
		comment := c.Query("comment")
		if comment == "" {
			comment = c.FormValue("comment")
		}
		msg := c.Query("msg")
		if msg == "" {
			msg = c.FormValue("msg")
		}
		return src.SendMsg(botKey, title, warn, msg, comment)
	})

	// msg from apps from develop
	app.Post("/:key/img", func(c *fiber.Ctx) error {
		sent_count++
		title := c.Query("title")
		if title == "" {
			title = c.FormValue("title")
		}
		msg := c.FormValue("msg")
		return src.SendImg(c.Params("key"), title, strings.Split(msg, "\\n")...)
	})

	logrus.Info(`
	/grafana-alert/:key  POST              -          sendCard
	/:key/img            POST         title/msg       sendImg
	/:key/txt            ALL  title/msg/warn/comment  sendMarkDown
	`)
	logrus.Fatal(app.Listen(":9000"))
}
